package main

import (
	"bufio"
	"encoding/json"
	"fmt"
	"io/ioutil"
	"net"
	"net/http"
	"strconv"
	"strings"
	"sync"
)

const qq = 1736979719

type Msg struct {
	Msg_type string
	Number   int
	Msg      string
}

type Group struct {
	Data []User `json:"data"`
}

type User struct {
	Group_id          int64  //群号
	User_id           int64  //QQ 号
	Nickname          string //昵称
	Card              string //群名片／备注
	Sex               string //性别
	Age               int32  //年龄
	Area              string //地区
	Join_time         int32  //加群时间
	Last_sent_time    int32  //最后发言时间
	Level             string //成员等级
	Role              string //角色
	Unfriendly        bool   //是否不良记录成员
	Title             string //专属头衔
	Title_expire_time int64  //专属头衔过期时间戳
	Card_changeable   bool   //是否允许修改群名片
}

//处理消息,群聊
type Message2 struct {
	Time        int64       `json:"time"`
	SelfId      int64       `json:"self_id"`
	PostType    string      `json:"post_type"`
	MessageType string      `json:"message_type"`
	SubType     string      `json:"sub_type"`
	MessageId   int32       `json:"message_id"`
	GroupId     int64       `json:"group_id"`
	UserId      int64       `json:"user_id"`
	Anonymous   anonymous   `json:"anonymous"` //匿名用户
	RawMessage  string      `json:"raw_message"`
	Font        int32       `json:"font"`
	Sender      sender      `json:"sender"`
	Message     interface{} `json:"message"` //消息
}

type anonymous struct {
	Id   int64  `json:"id"`
	Name string `json:"name"`
	Flag string `json:"flag"`
}

//发送消息者详细信息
type sender struct {
	UserId   int64  `json:"user_id"`
	Nickname string `json:"nickname"`
	Card     string `json:"card"`
	Sex      string `json:"sex"`
	Age      int32  `json:"age"`
	Area     string `json:"area"`
	Level    string `json:"level"`
	Role     string `json:"role"`
	Title    string `json:"title"`
}

//图片数据
type Image struct {
	Error string
	Data  []setu
}

type setu struct {
	Pid   int
	Title string
	Tags  []string
	Urls  Url
}

type Url struct {
	Original string
}

//智能回答
type Response struct {
	Result  int
	Content string
}

//消息体
type Body struct {
	Group_id int    `json:"group_id"`
	Message  string `json:"message"`
}

type Bodyprivate struct {
	User_id int    `json:"user_id"`
	Message string `json:"message"`
}

//socket链接qq号
func Sendmsg(m Msg) {
	var b Body
	var bp Bodyprivate
	var url string
	var x []byte
	if m.Msg_type == "group" {
		url = "http://127.0.0.1:5700/send_group_msg"
		b = Body{
			m.Number,
			m.Msg,
		}
		x, _ = json.Marshal(b)
	} else {
		url = "http://127.0.0.1:5700/send_private_msg"
		bp = Bodyprivate{
			m.Number,
			m.Msg,
		}
		x, _ = json.Marshal(bp)
	}
	res, err := http.Post(url, "application/json;charset=utf-8", strings.NewReader(string(x)))
	if err != nil {
		fmt.Println("post发送失败", err)
	}
	defer res.Body.Close()
	content, err := ioutil.ReadAll(res.Body)
	if err != nil {
		fmt.Println("读取响应失败")
	}
	fmt.Println("发送数据：", string(x))
	fmt.Println("响应数据：", string(content))

}

//获取群成员列表
func Getgroup(id int) {
	var url = "http://127.0.0.1:5700/get_group_member_list?group_id=" + strconv.Itoa(id)
	var gr Group
	resp, err := http.Get(url)
	if err != nil {
		fmt.Println("获取失败")
	}

	defer resp.Body.Close()
	body, err := ioutil.ReadAll(resp.Body)
	if err != nil {
		fmt.Println("读取失败")
	}
	err2 := json.Unmarshal(body, &gr)
	if err2 != nil {
		fmt.Println("解析失败:", err)
	}
	fmt.Println(gr.Data)
}

//删除消息
func Detmsg(u Message2) {
	s := "[CQ:tts,text=这是一条测试消息]"
	mes := Msg{
		u.MessageType,
		int(u.UserId),
		s,
	}
	Sendmsg(mes)
}

func process(conn net.Conn) {
	var mm Message2
	defer conn.Close()
	buf := make([]byte, 1000)
	n, err := conn.Read(buf[:])
	if err != nil {
		fmt.Println("获取数据出错了", err)
	}
	var s []byte
	for i, v := range buf[:n] {
		if v == 123 {
			s = buf[i:n]
			break
		}
	}
	fmt.Println("收到数据", string(s))
	err2 := json.Unmarshal(s, &mm)
	if err2 != nil {
		fmt.Println("unmarshal失败", err2)
	}
	fmt.Println(mm)
	conn.Write([]byte("HTTP/1.1 200 OK\r\n\r\nContent-Type: text/html\r\n\r\n"))
	//--------------------------事件处理
	if mm.MessageType == "group" {
		if mm.UserId != qq && strings.Contains(mm.RawMessage, "[CQ:at,qq=1736979719]") {
			l := strings.Index(mm.RawMessage, "[CQ:at,qq=1736979719]")
			if mm.RawMessage[len(mm.RawMessage)-1:] == "]" {
				mm.RawMessage = mm.RawMessage[:l] + mm.RawMessage[l+21:]
			} else {
				mm.RawMessage = mm.RawMessage[:l] + mm.RawMessage[l+22:]
			}
			fmt.Println(mm.RawMessage)
			Handle(mm) //处理信息
			//Detmsg(m)
		}
	} else {
		Handle(mm)
	}
}

//监听
func Mysocket() {
	listen, err := net.Listen("tcp", "127.0.0.1:5701")
	if err != nil {
		fmt.Println("服务器监听失败", err)
		return
	}
	for {
		conn, err := listen.Accept()
		if err != nil {
			fmt.Println("链接失败", err)
			continue
		}
		go process(conn)
	}
}

//处理消息
func Handle(u Message2) {
	var ty string
	var number int
	if u.MessageType == "private" {
		ty = "private"
		number = int(u.UserId)
	} else {
		ty = "group"
		number = int(u.GroupId)
	}
	if strings.Contains(u.RawMessage, "语音") {
		Detmsg(u)
		return
	}
	if strings.Contains(u.RawMessage, "se图") {
		HandleImage(u) //发送se图
	} else {
		var s string
		if strings.Contains(u.RawMessage, "你好") {
			s = u.Sender.Nickname + "好" + "[CQ:at,qq=" + strconv.FormatInt(u.UserId, 10) + "]"
		} else {
			var res Response
			resp, err := http.Get("http://api.qingyunke.com/api.php?key=free&appid=0&msg=" + u.RawMessage)
			if err != nil {
				fmt.Println("智能回答失败", err)
			}
			body := bufio.NewReader(resp.Body)
			b, _ := ioutil.ReadAll(body)
			json.Unmarshal(b, &res)
			s = res.Content + "[CQ:at,qq=" + strconv.FormatInt(u.UserId, 10) + "]"
		}
		mes := Msg{
			ty,
			number,
			s,
		}
		Sendmsg(mes)
	}
}

//私聊信息处理
func HandlePrivate(u Message2) {
	var s string
	s = "你是大笨蛋"
	mes := Msg{
		"private",
		int(u.UserId),
		s,
	}
	Sendmsg(mes)
}

func HandleImage(u Message2) {
	var im Image
	var ty string
	var number int
	if u.MessageType == "private" {
		ty = "private"
		number = int(u.UserId)
	} else {
		ty = "group"
		number = int(u.GroupId)
	}
	resp, err := http.Get("https://api.lolicon.app/setu/v2?r18=0")
	if err != nil {
		fmt.Println("图片加载失败", err)
	}
	defer resp.Body.Close()
	reader := bufio.NewReader(resp.Body)
	body, err2 := ioutil.ReadAll(reader)
	if err2 != nil {
		fmt.Println("读取失败")
	}
	json.Unmarshal(body, &im)
	fmt.Println(string(body))
	mes := Msg{
		ty,
		number,
		"[CQ:image,file=" + im.Data[0].Urls.Original + "]",
	}
	Sendmsg(mes)
}

func main() {
	var wg sync.WaitGroup
	wg.Add(1)
	//Getgroup(861335583)
	//Sendmsg(m)
	go Mysocket()
	wg.Wait()

}
